import { Injectable } from '@nestjs/common';
import { CreateSchedulerDto } from './dto/create-scheduler.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Scheduler } from './entities/scheduler.entity';
import { IsNull, Repository } from 'typeorm';
import { plainToInstance } from 'class-transformer';
import { validateParams } from 'src/common/utils';

@Injectable()
export class SchedulerService {
  constructor(
    @InjectRepository(Scheduler)
    private schedulerRepository: Repository<Scheduler>,
  ) {}

  async create(data: CreateSchedulerDto) {
    await validateParams(plainToInstance(CreateSchedulerDto, data));

    try {
      const result = this.schedulerRepository.save(data);
      return result;
    } catch (e) {}
  }

  async findAll() {
    try {
      const result = await this.schedulerRepository.find();
      return result;
    } catch (e) {}

    return [];
  }

  async deleteByName(name: string) {
    const exist = await this.schedulerRepository.findOne({ where: { name } });
    if (!exist) return;
    const { id } = exist;
    return await this.schedulerRepository.delete(id);
  }
}
